package dao

import (
	"database/sql"
	"fmt"
	"log"
)

const TableCompany = "company"

func (dbw *DbWorker) CompanyList(keyword string) []map[string]string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql_str := "select * from " + TableCompany
	if len(keyword) > 0 {
		sql_str += " where name like \"%" + keyword + "%\""
	}
	rows, err := dbw.Db.Query(sql_str)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		log.Fatal(err)
	}
	values := make([]sql.RawBytes, len(columns))
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		scanArgs[i] = &values[i]
	}

	u := make([]map[string]string, 0)
	for rows.Next() {
		err = rows.Scan(scanArgs...)
		if err != nil {
			panic(err.Error())
		}

		var value string
		var m = map[string]string{}
		for i, col := range values {
			if col == nil {
				value = ""
			} else {
				value = string(col)
			}
			m[columns[i]] = value
		}
		u = append(u, m)
	}
	return u
}

func (dbw *DbWorker) CompanySave(name string, intro string) string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql, err := dbw.Db.Prepare("insert into " + TableCompany + " (name, intro) values(?, ?)")
	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	ret, err := sql.Exec(name, intro)
	id, err := ret.LastInsertId()
	return fmt.Sprintf("%d", id)
}

func (dbw *DbWorker) CompanyUpdate(name string, intro string, id string) bool {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql, err := dbw.Db.Prepare("update " + TableCompany + " set name=?, intro=? where id=?")
	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	sql.Exec(name, intro, id)
	return true
}

func (dbw *DbWorker) CompanyDelete(id string) bool {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	sql, err := dbw.Db.Prepare("delete from " + TableCompany + " where id=?")
	if err != nil {
		log.Fatal(err)
		panic(err.Error())
	}
	sql.Exec(id)
	return true
}

func (dbw *DbWorker) CompanyQuery(company_id string) map[string]string {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	var id, name, intro, utime, ctime string

	scanArgs := []interface{}{&id, &name, &intro, &utime, &ctime}
	err := dbw.Db.QueryRow("select * from "+TableCompany+" where id=?", company_id).Scan(scanArgs...)
	if err != nil {
		panic(err.Error())
	}

	return map[string]string{
		"id":    string(id),
		"name":  string(name),
		"intro": string(intro),
		"utime": string(utime),
		"ctime": string(ctime),
	}
}

func (dbw *DbWorker) CompanyExists(name string) bool {
	dbw.MysqlConnect()
	defer dbw.Db.Close()

	var num int
	err := dbw.Db.QueryRow("select count(1) num from "+TableCompany+" where name=?", name).Scan(&num)
	if err != nil {
		panic(err.Error())
	}

	return num > 0
}
